<template>
  <gui-page :customHeader="true" class="gui-bg-white">
    <!-- 自定义头部导航 -->
    <!-- 自定义头部导航 -->
    <template v-slot:gHeader>
      <view
        style="height: 44px"
        class="gui-flex gui-nowrap gui-rows gui-align-items-center gui-bg-white gui-border-b"
      >
        <!-- 使用组件实现返回按钮及返回首页按钮 -->
        <gui-xhs-header-leading
          :home="false"
          @goBack="goBack"
        ></gui-xhs-header-leading>

        <!-- 导航文本此处也可以是其他自定义内容 -->
        <view
          class="gui-flex1 align-items-center gui-nowrap gui-flex gug-row"
          style="margin-left: 20rpx"
        >
          <image
            @tap="goCard(author.authorId)"
            style="width: 70rpx; height: 70rpx; border-radius: 70rpx"
            :src="author.avatarUrl"
            class="gui-slide-list-img xhs-margin-right-20"
            mode="aspectFill"
          ></image>

          <view class="xhs-font30 gui-flex1" style="line-height: 70rpx">{{
            author.authorName
          }}</view>

          <view>
            <gui-xhs-follow
              class="xhs-follow"
              :author="author"
              @cancelfollowAuthor="getAuthor()"
              @followAuthor="getAuthor()"
            ></gui-xhs-follow>
          </view>
        </view>
        <!-- 此处加一个右侧展位元素与左侧同宽，实现标题居中 -->
        <!-- 实际宽度请根据自己情况设置 -->
        <view
          @tap="confirm"
          class="xhs-font30"
          style="width: 80rpx; color: gray"
        >
          ···
        </view>
        <!-- 如果右侧有其他内容可以利用条件编译和定位来实现-->
      </view>
    </template>

    <template v-slot:gBody>
      <view style="background: #f8f8f8">
        <!--		只在加载时和加载完成时显示-->
        <gui-loadmore
          :loadMoreText="[
            '下滑加载历史记录',
            '更多数据加载中',
            '已加载全部数据',
            '暂无数据',
          ]"
          ref="loadmorecom2"
          :status="1"
        ></gui-loadmore>
        <!-- IM 消息展示区 -->
        <gui-xhs-im-message
          :msgs="chatList"
          group="group1"
          :userid="user.authorId"
        ></gui-xhs-im-message>
        <!-- 底部提交区 -->
        <gui-im-input
          @chooseImage="chooseImage"
          @sendText="sendText"
          @sendVoice="sendVoice"
        ></gui-im-input>
      </view>
    </template>
  </gui-page>
</template>
<script>
import getWebSocketClient from "@/Grace6/js/ws";
import parserHtml from "@/Grace6/js/parserHTML.js";
import commonMixin from "@/mixin/commonMinxin";

// 模拟消息数据
export default {
  mixins: [commonMixin],
  data() {
    return {
      user: uni.app.getStorage("user"),
      from: {},
      chatList: [],
      page: 1,
      hasMore: false,
      loadMore: false,
      socketMessageListener: null,
      onUnloadStatus: false,
      author: {},
    };
  },
  // 使用onBackPress监听返回按键
  // onBackPress(options) {
  // 	console.log(options)
  // 	if (options.from === 'backbutton') {
  // 		// 来自于导航条返回按钮或者系统返回按钮
  // 		// 在这里执行自定义逻辑
  // 		console.log('用户点击了返回按钮');
  // 		uni.app.navigate('/pages/login/login', 'reLaunch')
  // 		// 返回true表示拦截操作，不再继续执行返回操作
  // 		// 返回false或不返回表示不拦截操作，继续执行默认的返回行为
  // 		return true;
  // 	}
  // 	// 不拦截操作，继续执行默认的返回行为
  // 	return false;
  // },
  // onUnload(){
  // 	console.log('不再监听回调')
  // 	this.onUnloadStatus = true
  // },
  onLoad(e) {
    this.$nextTick(() => {
      this.from.authorId = e.authorId;
      this.from.authorName = e.authorName;

      uni.app.readAuthorMessage(e.authorId);
      this.getAuthor();
      this.getChatList();
      const wsClient = getWebSocketClient();
      // 定义自定义的消息处理函数（这里简单打印消息内容并进行一些模拟操作）
      // 调用onMessage方法传入自定义消息处理函数

      wsClient.onSocketMessageCallback = (res) => {
        if (res.handlerType != 5) {
          return;
        }
        const message = res.body;
        console.log(message);
        this.chatList.push(message);
        this.buildData();
        this.pageScroll();
        //当我收到了消息 且发送者不是我 将对方设置的所有消息 设置为 已读 如果不设置 下次进入主页获取未读消息 之后设置小红点
        console.log("我是聊天页面收到消息的提示");
        if (message.fromId != uni.app.getStorage("user").authorId) {
          uni.app.readAuthorMessage(message.fromId);
        }
      };
    });
  },
  onPullDownRefresh: function () {
    console.log("下拉刷新了");
    uni.stopPullDownRefresh();
    var status = this.$refs["loadmorecom2"].loadMoreStatus;
    if (status == 2) {
      console.log("不在请求了");
      return;
    }
    this.getChatList();
  },

  methods: {
    goCard(authorId) {
      return uni.app.goCard(authorId);
    },
    goBack() {
      uni.app.navigate("/pages/switchPages/message", "switchTab");
    },
    getAuthor() {
      uni.app.get(
        "/auth/getAuthor",
        { authorId: this.from.authorId },
        "",
        (res) => {
          console.log(res);
          this.author = res.data;
        },
      );
    },
    parserHtml(data) {
      return parserHtml.parserHTML(data);
    },
    buildData() {
      const records = this.chatList;
      for (let i = 0; i < records.length; i++) {
        const currentRecord = records[i];
        const currentCreateTime = new Date(currentRecord.createTime);
        let j = i + 1;
        while (j < records.length) {
          const nextRecord = records[j];
          const nextCreateTime = new Date(nextRecord.createTime);
          const timeDiff = (nextCreateTime - currentCreateTime) / 1000 / 60; // 计算时间差，单位换算为分钟
          if (timeDiff <= 2) {
            records[j].createTime = null;
            j++;
          } else {
            break;
          }
        }
      }
      console.log(records);
      this.chatList = records;
    },
    getChatList() {
      uni.app.get(
        "/auth/getChatList",
        {
          limit: 20,
          page: this.page,
          fromId: this.from.authorId,
          fromName: this.from.authorName,
        },
        "",
        (res) => {
          //倒序查询但是正序排列 时间早的在前面
          this.chatList.unshift(...res.data.records.reverse());
          //当前页数小于等于总页数
          if (this.page <= res.data.pages) {
            //等于1时执行页面滚动操作
            if (this.page == 1) {
              this.pageScroll();
            }
            if (this.page == res.data.pages) {
              this.$refs.loadmorecom2.nomore();
            } else {
              this.page++;
              this.$refs.loadmorecom2.stoploadmore();
            }
          } else {
            this.$refs.loadmorecom2.nomore();
            uni.app.msg("没有更多记录了");
          }
          this.buildData();
        },
      );
    },
    // 01 发送文本消息
    sendText: function (msg) {
      //提交给 IM 服务返回消息数据，添加到消息列表中
      //模拟IM 服务端返回消息
      var msg = {
        fromId: this.user.authorId,
        fromName: this.user.authorName,
        toId: this.from.authorId,
        toName: this.from.authorName,
        messageType: 0,
        content: msg,
        handlerType: "5",
      };
      const wsClient = getWebSocketClient();
      wsClient.sendMessage(JSON.stringify(msg));
    },
    // 02 选择图片
    chooseImage: function (img) {
      console.log("选择图片");
      // 选择后返回临时图片
      // 请提交给 IM 服务器上传，上传后会产生真实图片地址，
      // 具体逻辑视 IM 后端情况来实现
      // 然后 IM 服务返回消息数据，添加到消息列表中
      // 模拟IM 服务端返回消息
      var msg = {
        group: "group1",
        uindex: "10000",
        uname: "老兵张嘎",
        contentType: "img",
        uface:
          "https://images.unsplash.com/photo-1662695094714-966fc339a2e8?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwyNnx8fGVufDB8fHx8&auto=format&fit=crop&w=600&q=60",
        content: img,
        date: "刚刚",
      };

      // this.msgs.push(msg);
      this.pageScroll();
    },
    // 03 发送语音消息
    sendVoice: function (voice, vlength) {
      console.log(voice);
      // 录音后返回临时语音文件
      // 请提交给 IM 服务器上传，上传后会产生真实语音文件地址，
      // 具体逻辑视 IM 后端情况来实现
      // 然后 IM 服务返回消息数据，添加到消息列表中
      // 模拟IM 服务端返回消息
      var msg = {
        group: "group1",
        uindex: "10000",
        uname: "老兵张嘎",
        contentType: "voice",
        uface:
          "https://images.unsplash.com/photo-1662695089339-a2c24231a3ac?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxM3x8fGVufDB8fHx8&auto=format&fit=crop&w=100&q=60",
        content: voice,
        length: vlength,
        date: "刚刚",
      };
      this.msgs.push(msg);
      this.pageScroll();
    },
    // 滚动条滚动 [ 有新消息可以自动滚动到底部 ]
    pageScroll: function () {
      setTimeout(() => {
        uni.pageScrollTo({
          scrollTop: 999999 + Math.random(),
          duration: 200,
        });
      }, 200);
    },
  },
};
</script>
<style scoped></style>
